package com.unirn.medico;

import java.util.ArrayList;
import java.util.List;

import com.tads.medico.R;
import com.unirn.medico.banco.RepositorioConsulta;
import com.unirn.medico.listview.AdapterListView;
import com.unirn.medico.listview.ItemListView;
import com.unirn.medico.modelo.Consulta;
import com.unirn.medico.ws.ClientRest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class ListarActivity extends Activity implements OnItemClickListener, Runnable {
    private ListView listView;
    private AdapterListView adapterListView;
    private List<Consulta> listaConsultas;
    private ProgressDialog progressDialog;
    private Button btSalvarHistorico;
    
    private Bundle paramConsulta;
    
    private String dataInicial;
    private String dataFinal;
    private int idClinica;
    
    private RepositorioConsulta repositorioConsulta;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listar);

        listView = (ListView) findViewById(R.id.tela_consulta_listView);
        listView.setOnItemClickListener(this);
        
        btSalvarHistorico = (Button) findViewById(R.id.btSalvarHistorico);
		btSalvarHistorico.setOnClickListener(btSalvarHistoricoListener);
        
        Intent it = getIntent();
		paramConsulta = it.getExtras();

		if(paramConsulta != null){
			idClinica = paramConsulta.getInt("idClinica");
			dataInicial = paramConsulta.getString("dataInicialTxt");
			dataFinal = paramConsulta.getString("dataFinalTxt");
		}

        progressDialog = ProgressDialog.show(ListarActivity.this, "Aguarde", "Processando...");
		Thread thread = new Thread(ListarActivity.this);
		thread.start();
    }

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Consulta c = listaConsultas.get(arg2);
        showCustomDialog(c);
    }

    private void showCustomDialog(Consulta c) {
		final Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.custom_dialog);
		dialog.setTitle("Informações da consulta");

		TextView dialogPaciente = (TextView) dialog.findViewById(R.id.exibiNomeDialog);
		TextView dialogData = (TextView) dialog.findViewById(R.id.exibirDataDialog);
		TextView dialogHora = (TextView) dialog.findViewById(R.id.exibirHoraDialog);
		TextView dialogClinica = (TextView) dialog.findViewById(R.id.exibirClinicaDialog);
		TextView dialogStatus = (TextView) dialog.findViewById(R.id.exibirStatusDialog);

		dialogPaciente.setText(c.getPaciente());
		dialogData.setText(c.getDataConsulta());
		dialogHora.setText(c.getHoraConsulta());
		dialogClinica.setText(c.getClinica());
		dialogStatus.setText(c.getStatusConsulta());

		final Button ok = (Button) dialog.findViewById(R.id.bt_ok);
		ok.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		dialog.show();
	}
    
    private OnClickListener btSalvarHistoricoListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			exibirAlerta();
		}
	};
	
	private void exibirAlerta() {	
		AlertDialog.Builder dialog = new AlertDialog.Builder(ListarActivity.this);
		dialog.setMessage("Ao salvar seu historico seus dados anteriores serão perdidos. \nDeseja continuar?");
		
		dialog.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface di, int arg) {	
				repositorioConsulta = new RepositorioConsulta(ListarActivity.this);
				int qtdExcluidas = repositorioConsulta.deletarTodos();
				int qtd = repositorioConsulta.salvarLista(listaConsultas);

				Toast.makeText(ListarActivity.this, 
						"Consultas salvas: " + qtd + 
						"\nConsultas excluidas: " + qtdExcluidas, 
						Toast.LENGTH_LONG).show();
			}
		});

		dialog.setNegativeButton("Não", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface di, int arg) {
				
			}
		});
		
		dialog.setTitle("Aviso");
		dialog.show();
	}

	public void run() {
		ClientRest clienteRest = new ClientRest();
		int tipoClinica = idClinica;
		
		try {
			if(paramConsulta == null){
				listaConsultas = clienteRest.getListaMes();
			} else {
				listaConsultas = clienteRest.getListaConsulta(dataInicial, dataFinal, idClinica);
			}
			ArrayList<ItemListView> listInfoConsultas = new ArrayList<ItemListView>();
			
			for (Consulta consulta : listaConsultas) {
				if(consulta.getClinica().equalsIgnoreCase("Psicologia")){
					tipoClinica = 1;
				} else if(consulta.getClinica().equalsIgnoreCase("Fisioterapia")){
					tipoClinica = 2;
				} else {
					tipoClinica = 1;
				}
				
				ItemListView itens = new ItemListView(
						tipoClinica, 
						consulta.getPaciente(), 
						consulta.getDataConsulta() + " - " + 
						consulta.getHoraConsulta(), 
						consulta.getStatusConsulta()
				);
				
				listInfoConsultas.add(itens);
			}
			
			adapterListView = new AdapterListView(this, listInfoConsultas);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		handler.sendEmptyMessage(0);
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			
			listView.setAdapter(adapterListView);
		}
	};
}